const proxy = require('http-proxy-middleware');
const fs = require('fs');
const express = require('express');
const path = require('path');
const reload = require('./reload');

const filenames = fs.readdirSync(__dirname)
    .map(filename => filename.split('.')[0])
    .filter(filename =>
        filename !== 'index' &&
        filename !== 'ui' &&
        filename !== 'users' &&
        filename !== 'localtest' &&
        filename !== 'reload'
    );
module.exports = app => {
    // 代理远程服务器;
    // app.use([
    //     '/sales/api/v1',
    //     '/static/config.json',
    //     '/login',
    //     '/api/v1/login',
    //     '/api/v1/users',
    //     '/api/v1/files'
    // ], proxy({
    //     target: 'https://dev.chery-intl.sdt-int.com',
    //     // target: 'https://dmsuat.mychery.com',
    //     changeOrigin: true,
    // }));

    app.use(express.json()); // for parsing application/json
    app.use(express.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
    app.use('/api/v1/users', require('./users'));
    app.use('/api/v1/files', require('./files'));
    app.use('/sales/api/v1/ui', require('./ui'));
    // 禁止socket连接
    app.use('/api/v1/notifications', (req, res) => {
        res.sendStatus(403);
    });
    app.use('/api/v1/notifyChannel', (req, res) => {
        res.sendStatus(403);
    });

    filenames.forEach(filename => {
        const filePaht = path.join(__dirname, `./${filename}.js`);
        app.use(`/sales/api/v1/${filename}`, reload(filePaht));
    });
};
